package com.ggstream.scanner;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LinkGetter {
	private Pattern htmltag;
	public List<String> getLinks() {
		return links;
	}

	public List<String> getLabels() {
		return labels;
	}

	public List<String> getURLlinked() {
		return URLlinked;
	}

	private Pattern link;
	private final String root;

	List<String> links     = new ArrayList<String>();
	List<String> labels    = new ArrayList<String>();
	List<String> URLlinked = new ArrayList<String>();

	

	public LinkGetter(String root) {
		this.root = root;
		htmltag = Pattern.compile("<(A|a)\\b[^>]*(HREF|href)=\"[^>]*>(.*?)</(A|a)>");
		link    = Pattern.compile("(HREF|href)=\"[^>]*\">");
	}

	public void regerateLinks() {
		try {
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new URL(this.root).openStream()));
			String s;
			StringBuilder builder = new StringBuilder();
			while ((s = bufferedReader.readLine()) != null) {
				builder.append(s);
//				System.out.println("line : "+s);
			}

			Matcher tagmatch = htmltag.matcher(builder.toString());
			while (tagmatch.find()) {
				Matcher matcher = this.link.matcher(tagmatch.group());
				matcher.find();
				String link = matcher.group().replaceFirst("(HREF|href)=\"", "")
						.replaceFirst("\">", "");
				
				if (valid(link)) {
//					System.out.println("link : "+link + " label : " + label);
					if (link.endsWith(".mp3")) {
						links.add(makeAbsolute(this.root, link));
						String title = java.net.URLDecoder.decode( link, "UTF-8") ;
						labels.add(title);
					}
					// if it's a link, and not the "parent" directory
					if (link.endsWith("/") && !link.startsWith("/")) {
						URLlinked.add(makeAbsolute(this.root, link));
					}
					
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ;
	}

	private boolean valid(String s) {
		if (s.matches("javascript:.*|mailto:.*")) {
			return false;
		}
		return true;
	}

	private String makeAbsolute(String url, String link) {
		if (link.matches("http://.*")) {
			return link;
		}
		return (this.root+"/"+link) ;
	}
} 